<?php

class UploadPart {
	protected static $url;
	protected static $delimiter;
	protected static $instance;

	public function __construct() {
		static::$url = 'https://www.turnitin.com/t_submit.asp?aid=115365018&session-id=22c13237179546c3adb00e47a29a9bbd&lang=zh_hans';
		static::$delimiter = uniqid();
	}

	public function putPart($param) {
		$post_data = static::buildData($param);
		//var_dump($post_data);exit;
		$curl = curl_init(static::$url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
		curl_setopt($curl, CURLOPT_HTTPHEADER, [
			"Content-Type: multipart/form-data; boundary=" . static::$delimiter,
			"Content-Length: " . strlen($post_data),
		]);
		$response = curl_exec($curl);
		curl_close($curl);

		return $response;
	}

	private static function buildData($param) {
		$data = '';
		$eol = "\r\n";
		$upload = $param['upload'];
		unset($param['upload']);

		$filename = $param['userfile'];

		unset($param['userfile']);

		foreach ($param as $name => $content) {
			$data .= "--" . static::$delimiter . "\r\n"
				. 'Content-Disposition: form-data; name="' . $name . "\"\r\n\r\n"
				. $content . "\r\n";
		}
		// 拼接文件流
		$data .= "--" . static::$delimiter . $eol
			. 'Content-Disposition: form-data; name="userfile"; filename="' . $filename . '"' . "\r\n"
			. 'Content-Type:application/xlsx' . "\r\n\r\n";

		$data .= $upload . "\r\n";
		$data .= "--" . static::$delimiter . "--\r\n";
		return $data;
	}

	public static function getInstance() {
		if (!static::$instance) {
			static::$instance = new static();
		}
		return static::$instance;
	}

}

$fields = array(
	'userfile' => 'test.xlsx',
	'upload' => file_get_contents('/Users/lucckystar/Sites/puppet_task1/old2/test.xlsx'),
	'async_request' => 1,
	'userID' => '',
	'author_first' => 'li',
	'author_last' => 'lao',
	'title' => '文档',
	'db_doc' => '',
	'dropbox_filename' => '',
	'google_doc' => '',
	'google_auth_uri' => '',
	'token' => '',
	'submit_button' => '',
);
$part = UploadPart::getInstance()->putPart($fields);

$uuid = $part['uuid'];

echo $uuid;
exit();
